import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../components/Login.vue'
import Home from '../components/home.vue'
import Main from '../components/Main.vue'
import Users from '../components/users/Users.vue'

Vue.use(VueRouter)

  const routes = [
    {
      path:'/',
      redirect:'/login'
    },
    {
      path:'/login',
      component:Login
    },
    {
      path:'/home',
      component:Home,
      redirect:'/main',
      children:[
        {path:'/main',component:Main},
        {path:'/users',component:Users}
      ]
    }
]

const router = new VueRouter({
  routes
})

//如果用户退出登录，也就意味着用户不能访问首页了
//可以使用路由的导航守卫来实现这个功能
//to：就是我们要访问的路径
//from：表示从哪个路径跳转过来
//next：是个函数，表示放行
router.beforeEach((to,from,next)=>{
  if(to.path==='/login') return next()
  //首先我们要获取到sessionStorage中的token
  const tokenS=window.sessionStorage.getItem('token')
  //如果token不存在，我们就要强制跳转
  if(!tokenS) return next('login')
  //否则放行
  next()
})

export default router
